package com.chen.pfm.slice;

import com.chen.pfm.LoginAbility;
import com.chen.pfm.MainAbility;
import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.*;
import com.chen.pfm.utils.*;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;

import ohos.agp.window.service.WindowManager;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONObject;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import java.io.IOException;
import java.util.List;


public class LoginAbilitySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022001, "LoginAbilitySlice");
    Intent loginIntent = null;
    int isOk = 0;
    User user;
    String token;
    TextField useridTextField;
    TextField passwordTextField;
    Button register_but;
    Button login_but;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_login);
        useridTextField = (TextField) findComponentById(ResourceTable.Id_login_username);
        passwordTextField = (TextField) findComponentById(ResourceTable.Id_login_userpwd);
        register_but = (Button) findComponentById(ResourceTable.Id_login_register_but);
        login_but = (Button) findComponentById(ResourceTable.Id_login_but);
        //找到设置软键盘自适应的正确方法,在onStart()函数中设置,但没有效果，鸿蒙的问题
        this.getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);


        // present(new TestSlice(), new Intent());

        token = DataBaseUtil.GetValue(this, "token");
        if (token == null) {
            // 打印一条日志
            HiLog.info(LABEL, "欢迎你来到登门页面");
            //初始化登录资源
            initLogin();
        } else {
            isOk = 3;
            login();
        }
    }

    private void initLogin() {

        // 为注册按钮设置点击事件回调
        register_but.setClickedListener(component -> {
            HiLog.info(LABEL, "你点击了注册按钮,进行注册！");
            loginIntent = new Intent();
            Operation operation = new Intent.OperationBuilder().withDeviceId("")
                    .withAction("RegisterAbilitySlice")
                    .withBundleName(getBundleName())
                    .withAbilityName(LoginAbility.class.getName())
                    .build();
            loginIntent.setOperation(operation);
            startAbility(loginIntent);
        });
        // 为登录按钮设置点击事件回调
        login_but.setClickedListener(component -> {
            isOk = 0;
            if (useridTextField.getText() == null || "".equals(useridTextField.getText())) {
                //账号不能为空
                MyToast.showMyToast(this, "账号不能为空");

            } else if (passwordTextField.getText() == null || "".equals(passwordTextField.getText())) {
                //密码不能为空
                MyToast.showMyToast(this, "密码不能为空");
            } else {
                // 打印一条日志

                //启动线程去处理 --->需要执行比较耗时的任务（如下载文件、查询数据库），可创建其他线程来处理
                getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {//异步派发任务
                    ResultVo resultVo;
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userid", useridTextField.getText())
                            .add("password", passwordTextField.getText())
                            .build();

                    String getRequestjson = null;
                    try {
                        getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(MyUtil.login, requestBody);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (getRequestjson == null || getRequestjson.contains("not found")) {
                        getUITaskDispatcher().asyncDispatch(() -> {
                            MyToast.showMyToast(this, "找不到服务器，请确定服务器是否开启");
                        });
                        return;
                    }
                    Gson gson = new Gson();

                    try {
                        resultVo = gson.fromJson(getRequestjson, ResultVo.class);

                    } catch (Exception e) {
                        getUITaskDispatcher().asyncDispatch(() -> {
                            MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                        });
                        HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                        return;
                    }
                    if (resultVo == null) {//返回对象进行解析
                        HiLog.error(LABEL, "数据解析异常，返回结果集为空！");
                        getUITaskDispatcher().asyncDispatch(() -> {
                            MyToast.showMyToast(this, "数据解析异常，返回结果集为空！");
                        });
                        return;
                    } else if (resultVo.getCode() == 404) {
                        HiLog.error(LABEL, "404错误！");
                        getUITaskDispatcher().asyncDispatch(() -> {
                            MyToast.showMyToast(this, resultVo.getMsg());
                        });
                        return;
                    } else if (resultVo.getCode() == 200) {
                        getUITaskDispatcher().asyncDispatch(() -> {
                            MyToast.showMyToast(this, "正在为您加载资源...");
                        });

                        //将数据部分转化为json
                        String toJson = gson.toJson(resultVo.getData());
                        String msg = resultVo.getMsg();
                        //处理token
                        String token = DataBaseUtil.GetValue(this, "token");
                        if (token != null) {
                            DataBaseUtil.deleteValue(this, "token");
                        }
                        int i = DataBaseUtil.saveValue(this, "token", msg);
                        if (i == -1) {
                            HiLog.error(LABEL, "token无法保存！");
                            return;
                        }
                        //回传的数据一定是list<对象>的类型
                        ZSONArray zsonArray = ZSONArray.stringToZSONArray(toJson);

                        ZSONObject zsonObject = zsonArray.getZSONObject(0);
                        if (zsonObject == null) {
                            MyToast.showMyToast(this, "账号不存在！");
                            return;
                        }
                        int uid = zsonObject.getIntValue("uid");
                        //处理本地数据库
                        if (UserDBUtil.isExistByUid(this, uid)) {
                            try {
                                UserDBUtil.deleteByUid(this, uid);
                            } catch (DataAbilityRemoteException e) {
                                e.printStackTrace();
                            }
                        }
                        String userid = zsonObject.getString("userid");
                        String password = zsonObject.getString("password");
                        String username = zsonObject.getString("username");
                        String gender = zsonObject.getString("gender");
                        String birthday = zsonObject.getString("birthday");
                        String grade = zsonObject.getString("grade");
                        String createtime = zsonObject.getString("createtime");
                        user = new User(uid, userid, password, username, gender, birthday, grade, createtime);
                        //插入
                        int insert = UserDBUtil.insert(this, user);
                        //保存数据
                        i = DataBaseUtil.saveValue(this, "uid", String.valueOf(uid));
                        if (insert > 0 && i > 0) {

                            //************************************
                            //获取网络后台数据,线程3，得到账单数据
                            getRemoteStatementsData(MyUtil.findAllStatementByUid+ uid);
                            getRemoteClassifyData(MyUtil.findAllClassifyByUid+uid);
                            getRemoteAccountsData(MyUtil.findAllAccountByUid+uid);
                            //************************************

                        }
                    }
                });
            }
        });


    }

    private void login() {
        isOk++;
        if (isOk != 3) {
            return;
        } else {
            isOk = 0;
        }
        getUITaskDispatcher().asyncDispatch(() -> {
            MyToast.showMyToast(this, "数据加载完成！");
        });
        setResult( new Intent());
        terminateAbility();
    }

    public void getRemoteClassifyData(String url) {
        //1.启动一个线程去得到数据
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            Gson gson = new Gson();
            String getRequestjson = null;
            getRequestjson = HttpRequestUtil.sendGetRequest(this, url);
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "找不到服务器，请确定服务器是否开启");
                });
                return;
            }
            ResultVo resultVo;
            try {
                resultVo = gson.fromJson(getRequestjson, ResultVo.class);
            } catch (Exception e) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                });
                HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                return;
            }
            if (resultVo == null) {
                return;
            }
            if (resultVo.getCode() == 200) {
                HiLog.info(LABEL, "状态码正常");
                //将数据部分转化为json
                String toJson = gson.toJson(resultVo.getData());

                //  1.将总Json字符串转为一个ZSONObject
                ZSONArray zsonArray = ZSONArray.stringToZSONArray(toJson);
                for (int i = 0; i < zsonArray.size(); i++) {
                    ZSONObject c = zsonArray.getZSONObject(i);
                    String cid = c.getString("cid");
                    if (ClassifyDBUtil.isExistByCid(this, cid)) {
                        continue;
                    }
                    int uid = c.getIntValue("uid");
                    String cname = c.getString("cname");
                    int ctype = c.getIntValue("ctype");
                    String cctime = c.getString("cctime");
                    Classify classify = new Classify();
                    classify.setCid(cid);
                    classify.setCname(cname);
                    classify.setUid(uid);
                    classify.setCtype(ctype);
                    classify.setCctime(DateUtils.getStrTimeFromDateTime(DateUtils.getDateTimeFromStrTime(cctime)));
                    ClassifyDBUtil.insertClassify(this, classify);
                }
            } else {
                HiLog.info(LABEL, "数据请求异常");
            }
            login();
        });

    }


    public void getRemoteAccountsData(String url) {
        //1.启动一个线程去得到数据
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            String getRequestjson = null;
            Gson gson = new Gson();
            ResultVo resultVo;
            getRequestjson = HttpRequestUtil.sendGetRequest(this, url);
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "找不到服务器，请确定服务器是否开启");
                });
                return;
            }

            try {
                resultVo = gson.fromJson(getRequestjson, ResultVo.class);
            } catch (Exception e) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                });
                HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                return;
            }
            if (resultVo == null) {
                return;
            }
            if (resultVo.getCode() == 200) {
                HiLog.info(LABEL, "状态码正常");
                //将数据部分转化为json
                String toJson = gson.toJson(resultVo.getData());

                //  1.将总Json字符串转为一个ZSONObject
                ZSONArray zsonArray = ZSONArray.stringToZSONArray(toJson);
                for (int i = 0; i < zsonArray.size(); i++) {
                    ZSONObject c = zsonArray.getZSONObject(i);
                    String aid = c.getString("aid");
                    if (AccountDBUtil.isExistsAccountsByAid(this, aid)) {
                        continue;
                    }
                    int uid = c.getIntValue("uid");
                    String cid = c.getString("cid");
                    Double amoney = c.getDouble("amoney");
                    String aremark = c.getString("aremark");
                    String artime = c.getString("artime");
                    String actime = c.getString("actime");
                    Account account = new Account(aid, uid, amoney, cid, aremark, artime, actime);
                    //插入数据
                    AccountDBUtil.insertAccount(this, account);
                    HiLog.info(LABEL, "插入数据-->" + account.toString());
                }
            } else {
                HiLog.info(LABEL, "数据请求异常");
            }

            login();
            HiLog.info(LABEL, "Account资源获取中...task结束 isOk=" + isOk);
        });
    }


    public void getRemoteStatementsData(String url) {
        Gson gson = new Gson();
        //1.启动一个线程去得到数据
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            String getRequestjson = null;
            getRequestjson = HttpRequestUtil.sendGetRequest(this, url);
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "找不到服务器，请确定服务器是否开启");
                });
                return;
            }
            ResultVo resultVo;
            try {
                resultVo = gson.fromJson(getRequestjson, ResultVo.class);
            } catch (Exception e) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "gson解析返回对象Statements失败，请确定服务器是否开启");
                });
                HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                return;
            }
            if (resultVo == null) {
                return;
            }
            if (resultVo.getCode() == 200) {
                HiLog.info(LABEL, "状态码正常");
                //将数据部分转化为json
                String toJson = gson.toJson(resultVo.getData());
                //  1.将总Json字符串转为一个ZSONObject
                ZSONArray zsonArray = ZSONArray.stringToZSONArray(toJson);
                for (int i = 0; i < zsonArray.size(); i++) {
                    ZSONObject c = zsonArray.getZSONObject(i);
                    String sid = c.getString("sid");
                    if (StatementsDBUtil.isExistsMonthStatementsBySid(this, sid)) {
                        continue;
                    }
                    int uid = c.getIntValue("uid");
                    Double budget = c.getDouble("budget");
                    String sdate = c.getString("sdate");
                    String sctime = c.getString("sctime");
                    Statements statements = new Statements(sid, uid, budget, sdate, sctime);
                    StatementsDBUtil.insert(this, statements);
                    HiLog.info(LABEL, "插入数据-->" + statements.toString());
                }
            } else {
                HiLog.info(LABEL, "数据请求异常");
            }
            login();
            HiLog.info(LABEL, "Statements资源获取中...task结束 isOk=" + isOk);

        });
    }


    @Override
    protected void onActive() {
        setResult(new Intent());
        super.onActive();
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }
}
